import java.io.File;
import java.io.IOException;

public class DocxToPdfConverter {
    private static final String LIBREOFFICE_PATH = "C:/Program Files/LibreOffice/program/soffice.exe"; // LibreOffice安装路径

    public static void main(String[] args) {
        String inputFilePath = "D:\\project\\word-template\\output.docx";
        String outputFilePath = "D:\\project\\word-template\\outpdf2.pdf";

        try {
            convertDocxToPdf(inputFilePath, outputFilePath);
            System.out.println("Conversion completed successfully.");
        } catch (IOException | InterruptedException e) {
            System.err.println("Error during conversion: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void convertDocxToPdf(String inputFilePath, String outputFilePath) throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(
                LIBREOFFICE_PATH,
                "--headless",
                "--convert-to", "pdf",
                "--outdir", new File(outputFilePath).getParent(),
                inputFilePath
        );

        Process process = processBuilder.start();
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            throw new IOException("LibreOffice conversion process failed with exit code " + exitCode);
        }
    }
}
